//公用js文件，提供全局变量及公共方法

var _REQUEST_TYPE = 0; //全局变量，0访问本地文件，1访问服务器
var jsonUrl = "http://192.168.1.121:8080/Managerial_Network/"; //html页面数据访问接口
//设置placeHolder

/**
 * 重写window.console函数，解决IE不自动渲染此函数的问题（必须打开控制台刷新页面才可以正常运行）
 * @type {*|Console}
 */
window.console = window.console || (function() {
    var c = {};
    c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile = c.clear = c.exception = c.trace = c.assert = function() {};
    return c;
})();
//检查浏览器，提示相关信息
(function() {
    var _alertText = "";
    var ua = navigator.userAgent.toLowerCase(),
        uapv = navigator.appVersion;
    var isWinXp = ua.indexOf("nt 5.1") > -1; //XP系统
    var isIE = uapv.indexOf("MSIE 6.") > -1,
        isIE6 = uapv.indexOf("MSIE 6.") > -1,
        isIE7 = uapv.indexOf("MSIE 7.") > -1,
        isIE8 = uapv.indexOf("MSIE 8.") > -1,
        isIE9 = uapv.indexOf("MSIE 9.") > -1,
        isIE10 = uapv.indexOf("MSIE 10.") > -1;
    if (isIE6 || isIE7 || isIE8) {
        _alertText = "为了您更好的体验效果，建议您使用Chrome或者Firefox";
    }
    /* else if (isIE6 || isIE7 || isIE8) {        //IE较低版本
            _alertText = "为了您更好的体验效果，建议您使用IE较高版本IE11、chrome或者Firefox";
        }*/
    if (_alertText !== "") {
        setTimeout(function() {
            $(".cgw-device-tip").addClass("device-height-30");
            setTimeout(function() {
                $(".cgw-device-tip").html(_alertText + "<a style='color:red' href='javascript:hideTip();'>关闭提示</a>")
            }, 500)
        }, 3000);
        function hideTip() {
            $(".cgw-device-tip").hide();
        }
    }
})();

//获取显示器分辨率
var MyScreen = (function() {
    console.log("%c当前显示器分辨率:", "color:#fff;font-weight:bold;");
    console.log(screen.width + "*" + screen.height);
    return {
        screenHeight: screen.height,
        screenWidth: screen.width
    }
})();
//字符串超出省略 
String.prototype.cutstr = function(len) {
        var restr = this;
        var wlength = this.replace(/[^\x00-\xff]/g, "**").length;
        if (wlength > len) {
            for (var k = len / 2; k < this.length; k++) {
                if (this.substr(0, k).replace(/[^\x00-\xff]/g, "**").length >= len) {
                    restr = this.substr(0, k) + "...";
                    break;
                }
            }
        }
        return restr;
    }
    //格式化日期 DateFormat('yyyy_MM_dd hh:mm:ss:SS 星期w 第q季度') 
function DateFormat(format, date) {
    if (!date) {
        date = new Date();
    }
    var Week = ['日', '一', '二', '三', '四', '五', '六'];
    var o = {
        "y+": date.getYear(), //year 
        "M+": date.getMonth() + 1, //month  
        "d+": date.getDate(), //day  
        "h+": date.getHours(), //hour  
        "H+": date.getHours(), //hour 
        "m+": date.getMinutes(), //minute  
        "s+": date.getSeconds(), //second  
        "q+": Math.floor((date.getMonth() + 3) / 3), //quarter  
        "S": date.getMilliseconds(), //millisecond  
        "w": Week[date.getDay()]
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}
/**
 *自动转换流量数字，KB，MB，GB
 * @param v  单位为KB
 * @returns {string}
 */
function formatNetData(v) {

    var _mbValue = (v / 1024).toFixed(2), //MB
        _gbValue = (v / 1024 / 1024).toFixed(2); //GB
    var _re = v >= 1024 ? (v >= 1048576 ? _gbValue + "GB" : _mbValue + "MB") : v + "KB";
    return _re;
}
//返回两个数之间的随机数
function myRandom(min, max) {
    return Math.floor(min + Math.random() * (max - min));
}
//获取页面可视宽度 
function getPageViewWidth() {
    var d = document,
        a = d.compatMode == "BackCompat" ? d.body : d.documentElement;
    return a.clientWidth;
}
//获取url参数 
var getUrlParams = function(url) {
        if (!url) {
            url = location.search.substring(1);
        } else {
            url = url.substr(url.indexOf('?') + 1);
        }
        var args = new Object();   // 声明并初始化一个 "类" 
        // 获得地址(URL)"?"后面的字符串. 
        var query = decodeURI(url);
        var pairs = query.split("&");  // 分割URL(别忘了'&'是用来连接下一个参数) 
        for (var i = 0; i < pairs.length; i++) {
            var pos = pairs[i].indexOf('=');
            if (pos == -1) continue; // 它在找有等号的 数组[i] 
            var argname = pairs[i].substring(0, pos); // 参数名字 
            var value = pairs[i].substring(pos + 1);  // 参数值 
            // 以键值对的形式存放到"args"对象中 
            args[argname] = decodeURI(value);
        }
        return args;
    }
    //兼容IE的事件监听
function addHandler(target, eventType, handler) {
    if (target.addEventListener) { //主流浏览器,W3C
        addHandler = function(target, eventType, handler) {
            target.addEventListener(eventType, handler, false);
        };
    } else { //IE,非标准浏览器
        addHandler = function(target, eventType, handler) {
            target.attachEvent("on" + eventType, handler);
        };
    }
    //执行新的函数
    addHandler(target, eventType, handler);
}




function localGet(key) {
    return localStorage.getItem(key);
}

function localSave(key, value) {
    localStorage.removeItem(key);
    localStorage.setItem(key, value);
}

function localRemove(key) {
    localStorage.removeItem(key);
}
//判断某个值是否在数组中 
Array.prototype.in_array = function(e) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == e)
                return true;
        }
        return false;
    }
    /*获取鼠标位置*/
function getMousePos(event) {
    var pageX = event.pageX;
    var pageY = event.pageY;
    if (pageX == undefined) {
        pageX = event.clientX + document.body.scrollLeft || document.documentElement.scrollLeft;
    }
    if (pageY == undefined) {
        pageY = event.clientY + document.body.scrollTop || document.documentElement.scrollTop;
    }
    return {
        x: pageX,
        y: pageY
    }
}
//提示插件
var MyTip = (function() {
    var _dv = document.createElement("div"),
        _dvWidth, _dvHeight;
    _dv.className = "tooptip-charts";
    var _domTc = document.getElementsByClassName("tooptip-charts");
    return {
        /**
         * 显示提示框
         * @param mousep  鼠标对象
         * @param html  要显示的html文本
         */
        show: function(dom, mousep, html) {
            //鼠标位置
            _dv.innerHTML = html;
            _dv.style.left = (mousep.x - 60) + "px";
            _dv.style.top = (mousep.y - 70) + "px";
            if (_domTc.length < 1) {
                dom.body.appendChild(_dv);
            }
        },
        hide: function() {
            if (_domTc !== "undefined")
                _domTc[0].parentNode.removeChild(_domTc[0]);
        }
    }
})();
/**
 * 扩展echarts无数据时展示的内容
 * @type {{showError}}
 */
var MyShowError = (function() {
    return {
        showError: function(domObj, innerH) {
            if (domObj.dom) {
                if($(domObj.dom).find(".mc-chart-error")){  //存在该提示层，直接使用
                    $(domObj.dom).find(".mc-chart-error").show();
                    $(domObj.dom).find(".mc-chart-error").html(innerH);
                }else{                                      //不存在提示层,则创建并提示文字
                    var _newChild = $("<div>");
                    _newChild.addClass("mc-chart-error");
                    _newChild.html(innerH);
                    _newChild.appendTo($(domObj.dom));
                }
            }
        }
    }
})();
/**
 * echarts 公共Ajax方法，添加加载动画
 * @param domObj
 * @param reqUrl
 * @param params
 * @param callback
 */
$.myAjax = function(domObj, reqUrl, params, callback) {
    var _actionStart = reqUrl.lastIndexOf("\/"),
        _actionEnd = reqUrl.length - 1, //获取位置
        _actionName = reqUrl.substr(_actionStart + 1, _actionEnd); //获取action 或者 json 的名称
    var _ajaxObj = {
        url: reqUrl,
        type: "GET",
        data: params,
        dataType: "json",
        timeout: 10000,
        beforeSend: function () {  //发送请求之后添加”努力加载。。。"文字提示效果
            if($(domObj).children(".mc-chart-error").length>0){
                $(domObj).find(".mc-chart-error").show();
                $(domObj).find(".mc-chart-error").html("<span>努力的读取数据中...</span>");
            }else{
                var _newChild = $("<div>");
                _newChild.addClass("mc-chart-error");
                _newChild.html("<span>努力的读取数据中...</span>");
                _newChild.appendTo($(domObj.dom));
            }
         },
        success: function(data) {
            var _rd = data.result ? data.result : data;
            //判断接口数据仓库是否有数据
            var _seriesData = _rd.resultDatas.seriesData;
            if (_seriesData) {
                for (var i in _seriesData) {
                    if (_seriesData[i].length < 1) {  //接口数据仓库无数据
                        MyShowError.showError(domObj, "<span>暂无数据</span>");  //改变提示文字
                        return;
                    }
                }
            }
            callback(_rd);
        },
        error: function(er) {
            ajaxErrorFn(er,domObj);
            MyShowError.showError(domObj, "<span>数据请求超时</span>");
        }
    };
    if (reqUrl.match("json") === null) {
        _ajaxObj.dataType = "jsonp";
        _ajaxObj.jsonp = "callback";
    }
    $.ajax(_ajaxObj);
}
function ajaxErrorFn(er,domObj) {
    console.log("myAjax进入error函数，错误图表ID:"+domObj.dom.id);
}